package com.genghis.rapidcrm.kernel;

import com.genghis.rapidcrm.exception.RuntimeGoingException;
import com.genghis.rapidcrm.kernel.module.RapidModuleModel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;

public final class RapidModelBeanHelper {

    private static final Logger log = LoggerFactory.getLogger(RapidModelBeanHelper.class);

    public RapidModelBeanHelper() {
        // reserved.
    }

    private static <T> T getBean(String beanName, Class<T> requiredType, ApplicationContext applicationContext) {
        try {
            return applicationContext.getBean(beanName, requiredType);
        } catch (Exception e) {
            log.error("Get bean type " + requiredType.getSimpleName() + " name [ " + beanName + " ] error: " + e.getMessage());
        }
        return null;
    }

    public static RapidListViewModel getListViewModelBean(String moduleName, ApplicationContext applicationContext) {
        RapidListViewModel listViewModel = RapidModelBeanHelper.getBean(moduleName + "ListViewModel",
                RapidListViewModel.class, applicationContext);

        if (listViewModel == null) {
            listViewModel = RapidModelBeanHelper.getBean(RapidListViewModel.DEFAULT_LIST_VIEW_MODEL_BEAN_NAME,
                    RapidListViewModel.class, applicationContext);
        }
        if (listViewModel == null) {
            throw new RuntimeGoingException("Default RapidListViewModel name [ " +
                    RapidListViewModel.DEFAULT_LIST_VIEW_MODEL_BEAN_NAME + " ] not found!");
        }
        return listViewModel;
    }

    public static RapidModuleModel getModuleModelBean(String moduleName, ApplicationContext applicationContext) {
        RapidModuleModel moduleModel = RapidModelBeanHelper.getBean(moduleName + "ModuleModel",
                RapidModuleModel.class, applicationContext);
        if (moduleModel == null) {
            moduleModel = RapidModelBeanHelper.getBean(RapidModuleModel.DEFAULT_MODULE_BEAN_NAME,
                    RapidModuleModel.class, applicationContext);
        }
        if (moduleModel == null) {
            throw new RuntimeGoingException("Default RapidModuleModel name [ " +
                    RapidModuleModel.DEFAULT_MODULE_BEAN_NAME + " ] not found!");
        }
        return moduleModel;
    }
}